package com.mjfeed.fragment;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.mjfeed.activity.MainActivity;
import com.mjfeed.activity.ProductDetailActivity;
import com.mjfeed.activity.ProductListActivity;
import com.mjfeed.activity.R;
import com.mjfeed.adapter.BannerAdapter;
import com.mjfeed.adapter.GridViewAdapter;
import com.mjfeed.util.KeyBoardUtils;
import com.mjfeed.widget.MyGridView;
import com.mjfeed.zxing.CaptureActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

/**
 * 首页Fragment
 * @author zhaominglei
 * @date 2014-12-2
 * 
 */
public class HomeFragment extends BaseFragment implements OnClickListener{
	@SuppressWarnings("unused")
	private static final String TAG = HomeFragment.class.getSimpleName();
	private View view;
	private MainActivity activity;
	
	//首页顶部搜索
	private ImageView homeLogo;
	private EditText homeEdit;
	private ImageButton homeScan;
//	private ScrollViewExtend homeScroll;
	private String keyword;
	
	//首页轮播图
	private ViewGroup homeViewGroup;
	private ViewPager homeViewpager;
	private ImageView[] imageViews;
	private int[] lunboImages = new int[]{ R.drawable.fragment_home_lunbo1, R.drawable.fragment_home_lunbo2, R.drawable.fragment_home_lunbo3 };
	private int currentItem = 0; // 当前图片下标
	private ScheduledExecutorService scheduledExecutorService;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(android.os.Message message) {
			homeViewpager.setCurrentItem(currentItem);// 切换当前显示的图片
		};
	};
	
	//首页热门商品
	private MyGridView hotGridview;
	private int[] hotImages = new int[]{ R.drawable.fragment_home_hot1, R.drawable.fragment_home_hot2, R.drawable.fragment_home_hot3,
			R.drawable.fragment_home_hot1, R.drawable.fragment_home_hot2, R.drawable.fragment_home_hot3,
			R.drawable.fragment_home_hot1, R.drawable.fragment_home_hot2, R.drawable.fragment_home_hot3};
	
	//浏览更多
	private ImageView homeMore; 
	
	private Intent intent;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_home, container, false);
		return view;
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		view = getView();
		activity = (MainActivity)getActivity();
		super.onActivityCreated(savedInstanceState);
		
		init();
	}
	
	private void init() {
		homeLogo = (ImageView) view.findViewById(R.id.home_logo);
		homeEdit = (EditText) view.findViewById(R.id.home_edit);
		homeScan = (ImageButton) view.findViewById(R.id.home_scan);
//		homeScroll = (ScrollViewExtend) view.findViewById(R.id.home_scroll);
		
		homeViewGroup = (ViewGroup) view.findViewById(R.id.home_viewgroup);
		homeViewpager = (ViewPager) view.findViewById(R.id.home_viewpager);
		hotGridview = (MyGridView) view.findViewById(R.id.hotgridview);
		homeMore = (ImageView) view.findViewById(R.id.home_more);
		
		homeLogo.setOnClickListener(this);
		homeEdit.setSingleLine(true);
		homeEdit.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		homeEdit.setOnEditorActionListener(new HomeEditorActionListener());
		homeScan.setOnClickListener(this);
		
		int num = lunboImages.length;
		imageViews = new ImageView[num];
		for (int i = 0; i < num; i++) {
			imageViews[i] = new ImageView(activity);
			imageViews[i].setLayoutParams(new LayoutParams(20, 20));
			imageViews[i].setPadding(40, 0, 40, 0);
			if (i == 0) {
				imageViews[i].setBackgroundResource(R.drawable.dotchecked);
			} else {
				imageViews[i].setBackgroundResource(R.drawable.dotdefault);
			}
			homeViewGroup.addView(imageViews[i]);
		}
		
		homeViewpager.setAdapter(new BannerAdapter(activity));
		homeViewpager.setOnPageChangeListener(new HomePageChangeListener());
		hotGridview.setAdapter(new GridViewAdapter(activity, hotImages));
		hotGridview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				switch (position) {
				case 0:
					intent = new Intent(activity, ProductDetailActivity.class);
					intent.putExtra("productId", Long.valueOf(1));
					intent.putExtra("keyword", keyword);
					intent.putExtra("referer", "home");
					startActivity(intent);
					activity.finish();
					break;

				default:
					intent = new Intent(activity, ProductDetailActivity.class);
					intent.putExtra("productId", Long.valueOf(1));
					intent.putExtra("keyword", keyword);
					intent.putExtra("referer", "home");
					startActivity(intent);
					activity.finish();
					break;
				}
			}
		});
		
		homeMore.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.home_logo:
			Toast.makeText(v.getContext(), R.string.app_idea, Toast.LENGTH_SHORT).show();
			break;
		case R.id.home_scan:
			Intent intentScan = new Intent(activity, CaptureActivity.class);
			startActivity(intentScan);
			break;
		case R.id.home_more:
			Intent intentMore = new Intent(activity, ProductListActivity.class);
			intentMore.putExtra("referer", "home_more");
			startActivity(intentMore);
			activity.finish();
			break;

		default:
			break;
		}
	}

	@Override
	public void onStart() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 当Activity显示出来后，每两秒钟切换一次图片显示
		scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2, TimeUnit.SECONDS);
		super.onStart();
	}
	
	/**
	 * 换行切换任务
	 */
	private class ScrollTask implements Runnable {
		@Override
		public void run() {
			synchronized (homeViewpager) {
				currentItem = (currentItem + 1) % imageViews.length;
				handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
			}
		}

	}
	
	public class HomePageChangeListener implements OnPageChangeListener {
		private int oldPosition = 0;

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageSelected(int position) {
			currentItem = position;
			imageViews[position].setBackgroundResource(R.drawable.dotchecked);
			imageViews[oldPosition].setBackgroundResource(R.drawable.dotdefault);
			oldPosition = position;
		}
	}
	
	public class HomeEditorActionListener implements OnEditorActionListener {
		@Override
		public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
			if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
				KeyBoardUtils.closeKeybord(homeEdit, v.getContext());
				keyword = homeEdit.getText().toString();
				Intent intent = new Intent(activity , ProductListActivity.class);
				intent.putExtra("referer", "home_edit");
				intent.putExtra("keyword", keyword);
				startActivity(intent);
				activity.finish();
				return true;
			}
			return false;
		}
	}
}
